<template>
  <div class="login-box">
    <el-row>
      <el-col class="login-col" :xs="20" :md="6">
        <div class="login">
          <h2 class="login-title">账号登录</h2>
          <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="login-form">
            <el-form-item label-width="0" prop="username">
              <el-input placeholder="账号" type="text" v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label-width="0" prop="password">
              <el-input placeholder="密码" type="password" v-model="ruleForm.password" show-password></el-input>
            </el-form-item>
            <el-form-item label-width="0" prop="verify">
              <div class="verify-box">
                <el-input placeholder="验证码" type="text" v-model="ruleForm.verify_code"></el-input>
                <div class="img-box">
                  <span class="time-tip"></span>
                  <img class="img-code" :src="'http://127.0.0.1:8000/account/image-code/' + uuid" alt="" @click="handleRefreshImage">
                </div>
              </div>
            </el-form-item>
            <el-form-item label-width="0">
              <div class="login-button-box">
                <el-button class="" type="primary" @click="submitForm('ruleForm')">登录</el-button>
                <el-button @click="goPage('/register')">注册</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {loginIn} from '../api/apis'

export default {
  name: "Login",
  beforeMount() {
    this.generateUUID()
  },
  data() {
    const validateUserName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'));
      } else {
        if (this.ruleForm.username !== '') {
          if (this.ruleForm.username.length > 12 || this.ruleForm.username.length < 3) {
            callback(new Error('用户名必须在3~12个字符之间！'));
          }
          callback();
        }
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.password !== '') {
          callback();
        }
        callback();
      }
    };
    const validateVerifyCode = (rule, value, callback) => {
      if (this.ruleForm.verify_code === '') {
        callback(new Error('请输入验证码'));
      } else {
        if (this.ruleForm.verify_code !== '') {
          if (this.ruleForm.verify_code.length !== 4) {
            callback(new Error('4位字符'));
          }
          callback();
        }
      }
    };
    return {
      ruleForm: {
        username: '',
        password: '',
        verify_code: '',
      },
      uuid: '',
      timeTip: true,
      rules: {
        username: [
          {validator: validateUserName, trigger: 'blur'}
        ],
        password: [
          {validator: validatePass, trigger: 'blur'}
        ],
        verify: [
          {validator: validateVerifyCode, trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    generateUUID() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";
      this.uuid = s.join("");
    },
    submitForm(formName) {
      // console.log(formName)
      this.$refs[formName].validate((valid) => {
        // console.log(valid)
        if (valid) {
          // alert('submit!');
          this.handleLoginIn();
        } else {
          return false;
        }
      });
    },
    handleLoginIn() {
      let params = new URLSearchParams();
      params.append('username', this.ruleForm.username);
      params.append('password', this.ruleForm.password);
      params.append('verify_code', this.ruleForm.verify_code);
      params.append('uuid', this.uuid);
      loginIn(params)
          .then(response => {
            this.$store.commit('setName', response.data.username)
            this.$router.push({path: '/'})
            this.$store.commit('setActiveIndex', 0)
            this.$store.commit('setLoginStatus', '1')
          })
          .catch(failResponse => {
            let error_message = failResponse.data.message;
            this.$message.error(error_message);
          })
    },
    goPage(path) {
      this.$router.push({path: path})
    },
    handleRefreshImage(){
      if(this.timeTip) {
        this.timeTip = false
        let count = 60,
            tip = document.querySelector('.time-tip'),
            img = document.querySelector('.img-code'),
            timer = setInterval(() => {
          if (count > 0) {
            count--
            tip.innerHTML = count + 'S'
            img.style.cursor = 'not-allowed'
          } else {
            clearInterval(timer)
            tip.innerHTML = ''
            img.style.cursor = 'pointer'
            this.timeTip = true
          }
        }, 1000)
        tip.innerHTML = count + 'S'
        this.generateUUID()
      }
    },
  }
}
</script>

<style scoped>
@media only screen and (min-width: 992px) {
  .login-col {
    top: 170px !important;
    right: 60px !important;
    left: auto !important;
  }
}

.login-col {
  position: absolute;
  top: 150px;
  left: 0;
  right: 0;
  margin: 0 auto;
}

.login-box {
  position: fixed;
  width: 100%;
  height: 100%;
  background: url("http://h2.ioliu.cn/bing/Ceking_ZH-CN7314711047_1920x1080.jpg") 0 0 no-repeat;
}

.login {
  background-color: #ffffff;
  padding: 30px;
  margin: auto;
  border-radius: 15px;
}

.login-title {
  text-align: center;
}

.login-form {
  margin-top: 20px;
  vertical-align: center;
}

.login-button-box {
  display: flex;
  justify-content: space-between;
}

.login-form .login-button-box button {
  width: 48%;
}

.verify-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.verify-box .img-box{
  width: 140%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.verify-box .img-box img {
  max-height: 40px;
}
.img-code{
  cursor: pointer;
}
</style>
